package com.wonder.admin.controller;



import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.wonder.admin.domain.SysPrdIn;
import com.wonder.admin.request.SysRoleRequest;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.admin.service.SysPrdInService;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sunyf
 * @since 2023-11-13
 */
@Api(tags = "生产入库")
@RestController
@CrossOrigin
@RequestMapping("/api/sysPrdIn")
public class SysPrdInController {

    /**
     * Logger
     */
    private static final Logger _logger = LoggerFactory.getLogger(SysPrdInController.class);


    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    @Autowired
    private SysPrdInService sysPrdInService;


    @Autowired
    private IVtuzxKingdeeService vtuzxKingdeeService;



    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";//本地目录
    /**
     * 生产入库列表
     * @return
     */
    @RequestMapping("/prd_in_list")
    public AjaxResult<List<SysPrdIn>> getList(){
        return AjaxResult.success(sysPrdInService.list(new QueryWrapper<>()));
    }

    /**
     * 生产入库分页查询
     * @return
     */
    @RequestMapping("/prd_in_bill")
    public AjaxResult<CommonPage<SysPrdIn>> getPageList(@RequestBody SysRoleRequest sysRoleRequest){
        Page<SysPrdIn> page = new Page<>(sysRoleRequest.getPage(),sysRoleRequest.getLimit());
        IPage<SysPrdIn> list = sysPrdInService.selectList(sysRoleRequest,page);
        return AjaxResult.success(CommonPage.restPage(list));
    }

    /**
     * 添加数据
     * @param entity
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加",notes = "作者：sunyf")
    public AjaxResult<Long> insert(@RequestBody SysPrdIn entity){
        if (null != entity){
            //保存
            boolean rsg = sysPrdInService.save(entity);
            if(rsg){
                return AjaxResult.success(MessageUtils.message("insert.success"));
            }else {
                return AjaxResult.failed(MessageUtils.message("insert.fail"));
            }
        } else {
            return AjaxResult.failed(MessageUtils.message("insert.parameter.error"));
        }
    }

    @PostMapping("/getInfo")
    @ApiOperation(value = "获取入库对象",notes = "作者：sunyf")
    public AjaxResult<SysPrdIn> getById(@RequestBody Map<String,Object> map){
        if (map == null){
           return AjaxResult.failed(MessageUtils.message("search.not.exist"));
        }
        Long id = Long.parseLong(map.get("id").toString());
        SysPrdIn sysPrdIn = sysPrdInService.getById(id);
        if (null != sysPrdIn){
            return AjaxResult.success(sysPrdIn);
        } else {
            return AjaxResult.failed(MessageUtils.message("search.not.exist"));
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改数据",notes = "作者：sunyf")
    public AjaxResult<SysPrdIn> update(@RequestBody SysPrdIn entity){
        if(null != entity){
            boolean rsg = sysPrdInService.updateById(entity);
            if (rsg){
                return AjaxResult.success(MessageUtils.message("update.success"));
            } else {
                return AjaxResult.failed(MessageUtils.message("update.fail"));
            }
        } else {
            return AjaxResult.failed(MessageUtils.message("update.not.exist"));
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除",notes = "作者：sunyf")
    public AjaxResult<SysPrdIn> delete(@RequestBody Map<String,Object> map){
        if(map == null){
            return AjaxResult.failed(MessageUtils.message("search.not.exist"));
        }
        String id=map.get("id").toString();
        if(StringUtils.isBlank(id))
            return AjaxResult.failed(MessageUtils.message("input.parameter.error"));
        String[] roles=StringUtils.split(id, ',');
        ArrayList<Integer> ids=new ArrayList<Integer>();
        for(int i=0;i<roles.length;i++)
        {
            ids.add( Integer.parseInt(roles[i]));//整数数组
        }
        if(ids.contains(1))
            return AjaxResult.failed(MessageUtils.message("superadmin.cannot.delete"));
        boolean rsg = sysPrdInService.removeByIds(ids);
        if (rsg) {
            return AjaxResult.success(MessageUtils.message("delete.success"));
        }else {
            return AjaxResult.failed(MessageUtils.message("delete.not.exist"));
        }
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传附件",notes = "作者：sunyf")
    public AjaxResult<SysPrdIn> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//文件的原始名称
        String mainName = FileUtil.mainName(originalFilename);//文件前缀名称
        String extName = FileUtil.extName(originalFilename);//文件后缀
//        String projectPath = System.getProperty("user.dir");//项目的路径
//        String filesPath = projectPath + "\\files";//文件的存储目录
        File parentFile = new File(ROOT_PATH);//文件的父级目录
        if (!parentFile.exists()){
            parentFile.mkdirs();//如果父级目录不存在就创建
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        if (saveFile.exists()){//如果当前上传的文件已经存在了，就重新命名文件名称
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
            saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        }
        file.transferTo(saveFile);//存储文件到本地的硬盘
        String url = "http://" + ip + ":" + port + "/api/sysPrdIn/download/" + originalFilename;
        return AjaxResult.success(url);

    }

    /**
     * 文件下载
     * @param fileName
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{fileName}")
    @ApiOperation(value = "下载附件",notes = "作者：sunyf")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException{
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 附件下载
//        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 预览
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)){//如果当前文件不存在
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);//读取文件
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);//数组是一个字节数组，也就是文件的字节流数组
        outputStream.flush();
        outputStream.close();//关闭io流
    }



    /**
     * 查看详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "查看详情",notes = "作者：sunyf")
    public AjaxResult<SysPrdIn> getDetail(@RequestBody Map<String,Object> map){
        if (map == null){
            return AjaxResult.failed(MessageUtils.message("search.not.exist"));
        }
        Long id = Long.parseLong(map.get("id").toString());
        SysPrdIn sysPrdIn = sysPrdInService.getDetail(id);
        if (null != sysPrdIn){
            return AjaxResult.success(sysPrdIn);
        } else {
            return AjaxResult.failed(MessageUtils.message("search.not.exist"));
        }
    }

    public AjaxResult<SysPrdIn> get(){
        return null;
    }



    @PostMapping("/vtuzx_login")
    public AjaxResult vtuzxLogin() throws Exception{

        VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();

        //查询单位编码，直接传文字无效
        String cond = String.format("Fname = '%s'", "个");
        List<VtuzxMap> bd_customer = vtuzxKingdeeService.query(client, "BD_UNIT", new VtuzxArrayList<>(
                "FNumber",//单位编码
                "FNAME"//单位名称
        ), cond);
        String unit = "";
        if (bd_customer != null && bd_customer.size() > 0) {
            unit = bd_customer.get(0).getString("FNumber");
        }

        System.out.println(unit);

        return null;
    }
}
